package com.hxzy.rabbitmqpublisher.controller;

import com.hxzy.common.ExchangeConst;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.concurrent.FailureCallback;
import org.springframework.util.concurrent.SuccessCallback;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * @Author wy
 * @Description 路由交换机发消息(生产发送消息的确认机制)
 * @Date 2024/2/21 16:10
 * @Version 1.0
 */
@Log4j2
@RestController
public class DirectConfirmController {

    @Autowired
    private RabbitTemplate  rabbitTemplate;


    // http://localhost:18081/direct/send?msg=red路由键&key=red          queue01和queueu02同时由到消息
    // http://localhost:18081/direct/send?msg=blue路由键&key=blue        queue01由到消息
    // http://localhost:18081/direct/send?msg=yellow路由键&key=yellow    queue02由到消息
    // http://localhost:18081/direct/send?msg=yellow路由键&key=abc       消息丢失
    @GetMapping(value = "/direct/confirm/send")
    public String sendDirect(String msg,String key){
        //开启了消息投递确认机制    创建 correlated  类型
        // 2.全局唯一的消息ID，需要封装到CorrelationData中
        CorrelationData correlationData = new CorrelationData("order-"+ UUID.randomUUID().toString());

        //3、定义异步消息发送的回调接口 （SuccessCallback<? super T> , FailureCallback ）
        correlationData.getFuture().addCallback(result -> {
            if(result.isAck()){
                // 3.1.ack，消息成功
                log.info("消息发送成功, ID:{}", correlationData.getId());
            }else{
                // 3.2.nack，消息失败
                log.error("消息发送失败, ID:{}, 原因{}",correlationData.getId(), result.getReason());
            }
        }, ex -> {
            log.error("消息发送异常, ID:{}, 原因{}",correlationData.getId(),ex.getMessage());
        });


       this.rabbitTemplate.convertAndSend(ExchangeConst.QUEUE_DIRECT_EXCHANGE,key,msg,correlationData);
        return "direct发送成功";
    }
}
